import React, { Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Card,
  Icon,
  Button,
  Form,
  Divider,
  Col,
  Tag,
  Row,
  Input,
  message,
  Select,
  Modal,
  Popconfirm,
} from 'antd';
import Ellipsis from '@/components/Ellipsis';
import StandardTable from '@/components/StandardTable';
import AuthorizedButton from '@/components/AuthorizedButton';
import BucketOptForm from './component/BucketOptForm';

import styles from '../../styles/Manage.less';

const FormItem = Form.Item;
const { Option } = Select;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

@Form.create()
@connect(({ bucket, loading }) => ({
  bucket,
  loading: loading.models.bucket,
}))
class BucketManage extends React.Component {
  state = {
    modalVisible: false,
    expandForm: false,
    isEditForm: false,
    recordValue: {},
    formValues: {},
  };

  // 表格字段
  columns = [
    {
      title: '主键',
      dataIndex: 'id',
      render: text => (
        <div style={{ width: 50 }}>
          <Ellipsis tooltip lines={1}>
            {text}
          </Ellipsis>
        </div>
      ),
    },
    {
      title: '桶号',
      dataIndex: 'code',
      render: text => (
        <div style={{ width: 50 }}>
          <Ellipsis tooltip lines={1}>
            {text}
          </Ellipsis>
        </div>
      ),
    },
    { title: '桶名称', dataIndex: 'name' },
    {
      title: '程序类名',
      dataIndex: 'relatedClass',
      render: text => (
        <div style={{ width: 120 }}>
          <Ellipsis tooltip lines={1}>
            {text}
          </Ellipsis>
        </div>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: text => {
        if (text === 0) return <Tag color="#108ee9">待启用</Tag>;
        if (text === 1) return <Tag color="#2db7f5">启用中</Tag>;
        return <Tag color="#f50">已停用</Tag>;
      },
    },
    {
      title: '占用流量',
      dataIndex: 'allocatedFlow',
      render: text => <span>{text}%</span>,
    },
    {
      title: '白名单',
      dataIndex: 'whiteUser',
      render: text => (
        <div style={{ width: 60 }}>
          <Ellipsis tooltip lines={1}>
            {text}
          </Ellipsis>
        </div>
      ),
    },
    { title: '创建人', dataIndex: 'creator' },
    {
      title: '开始时间',
      dataIndex: 'start',
      render: (text, record) => {
        if (text === null) return null;
        return moment.unix(record.start).format('YYYY-MM-DD hh:mm:ss');
      },
    },
    {
      title: '结束时间',
      dataIndex: 'end',
      render: (text, record) => {
        if (text === null) return null;
        return moment.unix(record.end).format('YYYY-MM-DD hh:mm:ss');
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      render: (text, record) => (
        <Fragment>
          <AuthorizedButton mask={['EDIT']}>
            {record.status === 0 && (
              <Popconfirm
                placement="top"
                title="是否确认启用、启用后当前桶将被用于实验使用？"
                onConfirm={() => this.handleChangeStatus(record, 1)}
              >
                <a>启用</a>
              </Popconfirm>
            )}
          </AuthorizedButton>
          <AuthorizedButton mask={['EDIT']}>
            {record.status === 1 && (
              <Popconfirm
                placement="top"
                title="是否确认停用、停用后，桶实验将结束？"
                onConfirm={() => this.handleChangeStatus(record, 2)}
              >
                <a>停用</a>
              </Popconfirm>
            )}
          </AuthorizedButton>
          <AuthorizedButton mask={['EDIT']}>
            {record.status === 0 && (
              <a onClick={() => this.handleModalVisible(true, record, true)}>编辑</a>
            )}
          </AuthorizedButton>
          <AuthorizedButton mask={['DEL']}>
            <Popconfirm
              placement="top"
              title="是否确认删除，删除后数据将无法恢复，请确认？"
              onConfirm={() => this.handleDelete(record)}
            >
              <a>删除</a>
            </Popconfirm>
          </AuthorizedButton>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    const { dispatch, values } = this.props;
    dispatch({
      type: 'bucket/fetchByParams',
      payload: { params: { testId: values.id } },
    });
  }

  handleChangeStatus = (record, status) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'bucket/changeStatus',
      payload: { id: record.id, status },
      callback: () => {
        message.success('改变状态成功');
        // 重载数据
        this.reloadData();
      },
    });
  };

  // 删除操作处理
  handleDelete = record => {
    const { dispatch } = this.props;
    dispatch({
      type: 'bucket/remove',
      payload: record.id,
      callback: () => {
        message.success('删除成功');
        // 重载数据
        this.reloadData();
      },
    });
  };

  // 重新加载数据
  reloadData = () => {
    const { dispatch, values } = this.props;
    dispatch({
      type: 'bucket/fetchByParams',
      payload: { params: { testId: values.id } },
    });
  };

  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form, values: propValues } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'bucket/fetchByParams',
        payload: { params: { ...values, testId: propValues.id } },
      });
    });
  };

  // 分页、过滤、排序处理
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch, values } = this.props;
    const { formValues } = this.state;
    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }
    dispatch({
      type: 'bucket/fetchByParams',
      payload: {
        params: { ...params, testId: values.id },
        currentPage: pagination.current,
        pageSize: pagination.pageSize,
      },
    });
  };

  handleFormReset = () => {
    const { form, dispatch, values } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'bucket/fetchByParams',
      payload: { params: { testId: values.id } },
    });
  };

  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };

  handleModalVisible = (flag, record, isEdit) => {
    this.setState({
      modalVisible: !!flag,
      isEditForm: !!isEdit,
      recordValue: record || {},
    });
  };

  handleAdd = fields => {
    const { dispatch, values } = this.props;
    dispatch({
      type: 'bucket/add',
      payload: { ...fields, testId: values.id },
      callback: () => {
        message.success('添加成功');
        this.handleModalVisible();
        // 重载数据
        this.reloadData();
      },
    });
  };

  handleUpdate = fields => {
    const { dispatch, values } = this.props;
    dispatch({
      type: 'bucket/update',
      payload: { ...fields, testId: values.id },
      callback: () => {
        message.success('修改成功');
        this.handleModalVisible();
        // 重载数据
        this.reloadData();
      },
    });
  };

  // 查询表单
  renderForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem key="name" label="桶名称">
              {getFieldDecorator('name')(<Input placeholder="请输入桶名称" />)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem key="status" label="实验状态">
              {getFieldDecorator('status')(
                <Select placeholder="请选择">
                  <Option value={0}>待启用</Option>
                  <Option value={1}>启用中</Option>
                  <Option value={2}>已停用</Option>
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Divider type="horizontal" />
      </Form>
    );
  }

  render() {
    const {
      loading,
      bucket: { data },
    } = this.props;
    const { modalVisible, expandForm, recordValue, isEditForm } = this.state;
    const { bucketModalVisible, handleBucketModalVisible, values } = this.props;
    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
      handleUpdate: this.handleUpdate,
    };
    return (
      <Modal
        destroyOnClose
        maskClosable={false}
        width={1080}
        style={{ top: 20 }}
        bodyStyle={{ padding: '6px' }}
        title="实验桶管理"
        visible={bucketModalVisible}
        onCancel={() => handleBucketModalVisible(false, values)}
        onOk={() => handleBucketModalVisible(false, values)}
      >
        <Card bordered={false} style={{ overflow: 'scroll' }}>
          <div className={styles.Manage}>
            {expandForm && <div className={styles.ManageForm}>{this.renderForm()}</div>}
            <div className={styles.ManageOperator}>
              <AuthorizedButton mask={['ADD']}>
                <Button
                  icon="plus"
                  type="primary"
                  onClick={() => this.handleModalVisible(true, {}, false)}
                >
                  新增实验桶
                </Button>
              </AuthorizedButton>
              <span className={styles.querySubmitButtons}>
                <Button type="primary" onClick={this.handleSearch}>
                  筛选
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                  重置
                </Button>
                <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                  {expandForm ? '收起' : '展开'}
                  <Icon type={expandForm ? 'up' : 'down'} />
                </a>
              </span>
            </div>
            <StandardTable
              loading={loading}
              data={data}
              columns={this.columns}
              rowKey={record => record.id}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        {modalVisible && (
          <BucketOptForm
            {...parentMethods}
            isEdit={isEditForm}
            values={recordValue}
            modalVisible={modalVisible}
          />
        )}
      </Modal>
    );
  }
}

export default BucketManage;
